<template>
  <div class="mobile-fillInfo">
    <div class="form-container">
      <div class="title">{{ $t("form.apply.modal_title") }}</div>
      <div class="form">
        <div class="header">1. {{ $t("form.apply.title_1") }}</div>
        <a-form
          labelAlign="left"
          ref="formRef"
          :model="formData"
        >
          <a-form-item
            :label="$t('form.apply.form.item_1.label')"
            name="last_name"
            :rules="[
              {
                required: true,
                message: $t('form.apply.form.item_1.rules.error_1'),
                trigger: 'blur',
              },
            ]"
          >
            <a-input
              size="large"
              :maxlength="30"
              v-model:value.trim="formData.last_name"
              :placeholder="$t('form.apply.form.item_1.rules.error_1')"
            ></a-input>
          </a-form-item>
          <a-form-item
            :label="$t('form.apply.form.item_2.label')"
            name="first_name"
            :rules="[
              {
                required: true,
                message: $t('form.apply.form.item_2.rules.error_1'),
                trigger: 'blur',
              },
            ]"
          >
            <a-input
              size="large"
              :maxlength="30"
              v-model:value.trim="formData.first_name"
              :placeholder="$t('form.apply.form.item_2.rules.error_1')"
            ></a-input>
          </a-form-item>
          <a-form-item
            :label="`${$t('form.apply.form.item_3.label')}(DD/MM/YY)`"
            name="dob"
            :rules="[
              {
                required: true,
                message: $t('form.apply.form.item_3.rules.error_1'),
                trigger: 'blur',
              },
            ]"
          >
            <a-date-picker
              size="large"
              v-model:value="formData.dob"
              value-format="YYYY-MM-DD"
              placeholder="DD/MM/YY"
              :allowClear="false"
            >
              <template #suffixIcon></template>
            </a-date-picker>
          </a-form-item>
          <a-form-item
            :label="$t('form.apply.form.item_4.label')"
            name="country"
            :rules="[
              {
                required: true,
                message: $t('form.apply.form.item_4.rules.error_1'),
                trigger: 'blur',
              },
            ]"
          >
            <a-select
              v-model:value="formData.country"
              show-search
              :placeholder="$t('form.apply.form.item_4.rules.error_1')"
              :options="countryStore.countrySelectOptions"
              :filter-option="filterOption"
            ></a-select>
          </a-form-item>
          <a-form-item
            :label="$t('form.apply.form.item_5.label')"
            name="telephone"
            :rules="[
              { required: true, validator: checkPhone, trigger: 'blur' },
            ]"
          >
            <a-input
              size="large"
              :maxlength="30"
              v-model:value.trim="formData.telephone"
              :placeholder="$t('form.apply.form.item_5.rules.error_1')"
            ></a-input>
          </a-form-item>
          <a-form-item
            :label="$t('form.apply.form.item_7.label')"
            name="email"
            :rules="[
              { required: true, validator: checkEmail, trigger: 'blur' },
            ]"
          >
            <a-input
              size="large"
              :maxlength="30"
              v-model:value.trim="formData.email"
              :placeholder="$t('form.apply.form.item_7.rules.error_1')"
            ></a-input>
          </a-form-item>
          <a-form-item
            class="upload_id_img"
            :label="$t('form.apply.form.item_8.label')"
            name="fileList"
            :rules="[
              { required: true, validator: checkFileList, trigger: 'blur' },
            ]"
          >
            <a-upload
              list-type="picture-card"
              v-model:file-list="formData.fileList"
              :maxCount="1"
            >
              <div>
                <PlusOutlined />
                <div class="upload-text">{{ $t("btnText.upload_idcard") }}</div>
              </div>
            </a-upload>
          </a-form-item>
        </a-form>
      </div>
      <div class="form">
        <div class="header">2. 2. {{ $t("form.apply.title_2") }}</div>
        <div class="form">
          <template v-for="(item, index) in checkList" :key="item.title">
            <div class="table">
              <template v-if="item.has_son == 'yes'">
                <div class="table-header border-bottom cell">
                  {{ item.title }}
                </div>
                <div class="table-content">
                  <div
                    class="table-row border-bottom"
                    :class="[i % 2 == 0 ? 'background' : '']"
                    v-for="(item2, i) in item.list2"
                    :key="i"
                  >
                    <div class="cell">
                      <a-checkbox v-model:checked="item2.checked">{{
                        item2.title
                      }}</a-checkbox>
                    </div>
                  </div>
                </div>
              </template>
              <template v-else-if="item.has_son == 'no'">
                <div class="table-content">
                  <div
                    class="table-row border-bottom"
                    :class="[index % 2 == 0 ? 'background' : '']"
                  >
                    <div class="cell">
                      <a-checkbox v-model:checked="item.checked">{{
                        item.title
                      }}</a-checkbox>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </template>
        </div>
      </div>
      <div class="form">
        <div class="header">3. {{ $t("form.apply.title_3") }}</div>
        <div class="declare-checkbox">
          <a-checkbox-group
            v-model:value="declareValues"
            :options="declareOptions"
          />
        </div>
      </div>
    </div>
    <div class="btn">
      <a-button type="default" @click="checkAll">{{
        $t("btnText.check_all")
      }}</a-button>
      <a-button type="primary" @click="submit">{{
        $t("btnText.imed_submit")
      }}</a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from "vue-router";
import img from "~/assets/images/common/id-card.png";
import { message } from "ant-design-vue";
import {
  computed,
  getCurrentInstance,
  onBeforeMount,
  onMounted,
  ref,
} from "vue";
import type {
  CourseSubmitCreateParams,
  OutlineItem,
} from "../../types/aviation";
import { RegMobile, RegEmail } from "../../data/reg";
import { useMemberStore, useCountryStore, useGlobalStore } from "../../store";
import { postUploadSingleImg } from "../../api/api";
import { postCourseApply } from "../../api/aviation";
const memberStore = useMemberStore();
const countryStore = useCountryStore();
const globalStore = useGlobalStore();
const checkList = ref([]);

const router = useRouter();
const route = useRoute();

const declareOptions = computed(() => {
  return globalStore?.aviationDetailApplyDeclare?.map((item: any) => {
    return { label: item.title, value: item.title };
  });
});

const declareValues = ref([]);

const goBack = () => {
  sessionStorage.removeItem("fill_apply_list");
  close();
};

onBeforeMount(() => {
  let list = sessionStorage.getItem("fill_apply_list");
  if (list) {
    checkList.value = JSON.parse(list);
  }
});

const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;

const filterOption = (input: string, option: any) => {
  return option.codes?.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

const checkAll = () => {
  checkList.value.map((item: OutlineItem) => {
    item.checked = true;
    item.list2!.map((item2: OutlineItem) => {
      item2.checked = true;
    });
  });
};

const clearCheckAll = () => {
  checkList.value.map((item: OutlineItem) => {
    item.checked = false;
    item.list2!.map((item2: OutlineItem) => {
      item2.checked = false;
    });
  });
};
const checkPhone = async (_rule: any, value: string) => {
  if (!value) {
    return Promise.reject($t("form.apply.form.item_5.rules.error_1"));
  }
  let regPhone = RegMobile;
  if (!regPhone.test(value)) {
    return Promise.reject($t("reg_rules.mobile"));
  } else {
    return Promise.resolve();
  }
};

const checkEmail = async (_rule: any, value: string) => {
  if (!value) {
    return Promise.reject($t("form.apply.form.item_7.rules.error_1"));
  }
  let regEmail = RegEmail;
  if (!regEmail.test(value)) {
    return Promise.reject($t("reg_rules.email"));
  } else {
    return Promise.resolve();
  }
};

const checkFileList = async (_rule: any, value: string) => {
  if (value.length !== 2) {
    return Promise.reject($t("form.apply.form.item_8.rules.error_1"));
  } else {
    return Promise.resolve();
  }
};

// 表单数据
const formData = ref<CourseSubmitCreateParams & { fileList: any[] }>({
  last_name: memberStore.profile?.last_name || "",
  first_name: memberStore.profile?.first_name || "",
  country: countryStore.getCountryById(memberStore.profile?.country_id!) || "",
  dob: memberStore.profile?.birthday || "",
  telephone: memberStore.profile?.mobile || "",
  card_no: "",
  email: memberStore.profile?.email || "",
  identity_document: [],
  course_id: 0,
  course_ku_list_id: "",
  fileList: [],
});

const formRef = ref();
const submitLoading = ref(false);
const submit = () => {
  formRef.value.validate().then(async () => {
    if (
      declareValues.value.length !==
      globalStore?.aviationDetailApplyDeclare?.length
    ) {
      message.warning($t("message.agree_read"));
      return;
    }
    submitLoading.value = true;
    let file1 = formData.value.fileList[0].originFileObj;
    let formDataValue = new FormData();
    formDataValue.append("file", file1);
    let { img: img1 } = await postUploadSingleImg(formDataValue);
    // 获取数据
    formData.value.course_id = route.query.id;
    formData.value.course_ku_list_id = getCheckListItem();
    formData.value.identity_document = [img1!];
    if (isNaN(parseInt(formData.value.country))) {
      formData.value.country = countryStore.getCountryIdByTitle(
        formData.value.country
      );
    }
    // 申请报名请求接口
    let res = await postCourseApply(formData.value);
    if (res.code === 200) {
      message.success($t("message.apply_success"));
    } else {
      submitLoading.value = false;
      message.error($t("message.error.submit"));
    }
    goto(-1)
  });
};

const getCheckListItem = () => {
  let arr: number[] = [];
  checkList.value.map((item: OutlineItem) => {
    if (item.has_son == "yes") {
      item.list2?.forEach((item2) => {
        if (item2.checked) {
          arr.push(item2.id);
        }
      });
    } else {
      if (item.checked) {
        arr.push(item.id);
      }
    }
  });
  return arr.join(",");
};
</script>
<style scoped lang="less">
.mobile-fillInfo {
  position: fixed;
  z-index: 9;
  inset: 0;
  top: var(--yd-header-height);
  background-color: #fff;
  height: calc(100svh - var(--yd-header-height));
  display: flex;
  flex-direction: column;
  .form:last-child {
    margin-top: 164px;
  }
  .declare-checkbox {
    padding: 82px;
    :deep(.ant-checkbox-group) {
      flex-direction: column;
      gap: 82px;
      .ant-checkbox + span {
        white-space: normal;
      }
    }
  }
  .form-container {
    flex: 1;
    padding: 82px;
    overflow-y: auto;
    :deep(.ant-form) {
      .ant-form-item-label {
        flex: none;
        width: 700px;
        display: flex;
        align-items: center;
        padding-bottom: 0;
        label {
          font-size: 82px;
        }
      }
      .ant-form-item-control {
        flex: 1;
      }
      .ant-form-item {
        padding: 82px 0;
        margin-bottom: 0;
        flex: 1;
        border-bottom: 3px solid #e6edf2;
        &:last-child {
          padding-bottom: 82px;
        }
        .ant-upload-wrapper {
          display: block;
        }
        &:last-child > div {
          .ant-form-item-label {
            padding: 82px 0;
          }
          .ant-form-item-control {
            flex: 0 0 100%;
          }
          .ant-upload-list {
            display: flex;
            gap: 56px;
            &::before {
              content: none;
            }
            & > div {
              flex: 1;
              margin: 0;
            }
            .ant-upload,
            .ant-upload-list-item {
              height: 850px;
              max-width: 850px;
            }
            .ant-upload-list-item {
              display: flex;
              overflow: hidden;
              padding: 0;
              &::before {
                width: 100%;
                height: 100%;
                left: 0;
                top: 0;
              }
              .ant-upload-list-item-actions {
                display: flex;
                justify-content: center;
                gap: 82px;
                .ant-btn {
                  height: auto !important;
                  padding: 0 !important;
                }
              }
            }
            .ant-upload {
              svg {
                fill: #ccd6de;
                width: 246px;
                height: 246px;
              }
              .upload-text {
                font-size: 72px;
                color: #ccd6de;
              }
            }
          }
        }
      }
      .ant-select-selector {
        box-shadow: none !important;
        border-color: transparent !important;
        text-align: right;
        .ant-select-selection-item {
          padding-right: 150px;
        }
      }
      .ant-input,
      .ant-select,
      .ant-select-selector,
      .ant-picker {
        padding-right: 0;
        border-color: transparent;
        box-shadow: 0 0 0 transparent;
        &:hover {
          border-color: transparent;
        }
      }
      .ant-picker {
        width: 100%;
      }
      .ant-input,
      .ant-picker input {
        text-align: right;
        &::placeholder {
          text-align: right;
        }
      }
    }
    .title {
      font-weight: 500;
      font-size: 92px;
      color: #172026;
      margin-bottom: 82px;
    }
    .form {
      .header {
        padding: 61px 82px;
        color: #fff;
        background-color: #3d88f2;
        font-size: 82px;
      }
    }
  }
  .btn {
    border-top: 3px solid #e6edf2;
    justify-content: space-between;
    padding: 82px;
    padding-top: 41px;
    .ant-btn:first-child {
      background-color: #e6edf2;
      border-color: transparent;
    }
    .ant-btn {
      width: 850px;
    }
  }
  :deep(.ant-form) {
    .ant-form-item-explain-error {
      text-align: right;
    }
    .upload_id_img {
      .ant-form-item-explain-error {
        text-align: left;
      }
    }
  }
  :deep(.table) {
    text-align: left;
    border: 1px solid #e6edf2;
    margin-bottom: 82px;
    &:last-child {
      margin-bottom: 82px;
    }

    .table-header {
      font-size: 72px;
      text-align: left;
    }
    .cell {
      padding: 82px !important;
    }
    .table-row:last-child {
      border-bottom-color: transparent !important;
    }
  }
}
</style>
